package com.beijiteshop.libcommon.view

import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.widget.TextView
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.lifecycleScope
import com.beijiteshop.libcommon.R
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * Author: LiaoZhongKai.
 * Date: 2020/3/30
 * Function:
 */
class LoadingDialog() : DialogFragment() {
    companion object{
        private const val TAG = "LOADING_DIALOG"
        private const val BUNDLE_TEXT = "bundle_text"

        private var mDialogFragment: LoadingDialog? = null

        fun showDialog(fm: FragmentManager, text: String? = null): LoadingDialog{
            mDialogFragment = LoadingDialog()
            if (text != null){
                val bundle = Bundle()
                bundle.putString(BUNDLE_TEXT,text)
                mDialogFragment!!.arguments = bundle
            }
            mDialogFragment!!.show(fm,
                TAG
            )
            return mDialogFragment!!
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.loading_dialog,container,false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        dialog?.apply {
            requestWindowFeature(Window.FEATURE_NO_TITLE)
            window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
            setCanceledOnTouchOutside(false)
            setCancelable(false)
        }
        val text = arguments?.getString(BUNDLE_TEXT)
        if (!text.isNullOrEmpty()){
            view.findViewById<TextView>(R.id.loading_dialog_tv).text = text
        }
    }

    fun dismissDialog(){
        lifecycleScope.launch {
            delay(600)
            mDialogFragment?.dismiss()
        }
    }
}